<template>
    <el-dialog :visible="true"
               title="编辑人员信息"
               append-to-body
               destroy-on-close
               :before-close="() => $emit('close')"
    >
        <el-tabs :active-name="activeTab">

            <el-tab-pane :label="tabs[0].label" :name="tabs[0].name">
                <base-info-editor :recorder="recorder.baseInfo" :ref="tabs[0].name" @age-change="handleAgeChange"/>
            </el-tab-pane>

            <el-tab-pane :label="tabs[1].label" :name="tabs[1].name">
                <extend-info-editor :recorder="recorder.extendInfo" :ref="tabs[1].name" :age="age"/>
            </el-tab-pane>

        </el-tabs>

        <div slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click="handleSubmit">保存</el-button>
        </div>

    </el-dialog>
</template>

<script>
    import UserInfo from "./UserInfo";
    import BaseInfoEditor from "./BaseInfoEditor";
    import ExtendInfoEditor from "./ExtendInfoEditor";

    const tabs = [
        {
            label: '基本信息',
            name: 'baseInfo',
        },
        {
            label: '扩展信息',
            name: 'extendInfo',
        },
    ];

    export default {
        components: {BaseInfoEditor, ExtendInfoEditor},
        data() {
            return {
                activeTab: tabs[0].name,
                tabs,
                age: this.recorder.baseInfo.age,
            };
        },
        methods: {
            async handleSubmit() {
                const result = {};
                let validateSuccess = true;
                for (let tab of this.tabs) {
                    const t = this.$refs[tab.name];
                    try {
                        result[tab.name] = await t.validate();
                    } catch (e) {
                        validateSuccess = false;
                        this.activeTab = tab.name;
                        console.log(e);
                    }
                }

                if (validateSuccess) {
                    result.baseInfo.id = this.recorder.baseInfo.id;
                    this.$emit('close', result);
                }
            },
            handleAgeChange (age) {
                this.age = age;
            },
        },
        props: {
            recorder: {
                type: Object,
                default: () => new UserInfo(),
            },
        },
    };
</script>
